package com.springcloudalibaba.serviceJournal.rocketmq;

import com.alibaba.fastjson.JSONObject;
import com.springcloudalibaba.bclass.base.BaseMsgEntity;
import com.springcloudalibaba.bclass.constant.RocketMqTopicConstant;
import com.springcloudalibaba.bclass.util.ConvertUtils;
import com.springcloudalibaba.bclass.util.LoggerUtil;
import com.springcloudalibaba.serviceJournal.entity.MsgEntity;
import com.springcloudalibaba.serviceJournal.service.MsgService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.MessageFormat;

/**
 * @描述: 短信监听器
 * @作者: lixing
 * @日期 2021/6/14 10:17
 */
@Component
@RocketMQMessageListener(
        topic = RocketMqTopicConstant.LOG_TOPIC,                       // topic：和消费者发送的topic相同
        consumerGroup = "MsgListener",             // group：不需要和生产者group相同 RocketMqTopicConstant.PROJECTNAME
        selectorExpression = RocketMqTopicConstant.LOG_TAG_MSG)        // tag: * 表示所有
public class MsgListener implements RocketMQListener<BaseMsgEntity> {

    @Resource
    private MsgService msgService;

    @Override
    public void onMessage(BaseMsgEntity baseMsgEntity) {
        if (null == baseMsgEntity) {
            LoggerUtil.info("MsgListener 入参为空");
        } else {
            boolean flag = true;
            try {
                MsgEntity msgEntity = ConvertUtils.convert(baseMsgEntity, MsgEntity.class);
                flag = msgService.save(msgEntity);
                if (!flag) {
                    LoggerUtil.info("LogListener 添加失败");
                }
            } catch (Exception e) {
                flag = false;
                LoggerUtil.info(MessageFormat.format("MsgListener 添加出错: {0}", e.getMessage()));
            } finally {
                if (!flag) {
                    LoggerUtil.info(JSONObject.toJSONString(baseMsgEntity));
                    LoggerUtil.info("");
                }
            }
        }
    }
}
